using Dapper;
using Eno.Domain.Repositories;
using Npgsql;

namespace Eno.Infrastructure.InfRepositories;

public class CombineRolePermissionRepository : IRoleToPermissionRepository
{
    public readonly string _connectionString;

    public CombineRolePermissionRepository(string connectionString)
    {
        _connectionString = connectionString;
    }
    public async Task<int> AppointPermissionToRole(Guid rId, Guid pId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"insert into app_roles_permissions(""PermissionsID"",""RolesID"") values(@PID,@RID)";
        var number = await conn.ExecuteAsync(sql, new { PID = pId, RID = rId });
        return number;
    }

    public async Task<int> RemovePermissionInRole(Guid rId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"delete from app_roles_permissions where ""RolesID""=@ID ";
        return await conn.ExecuteAsync(sql, new { ID = rId });
    }

    public async Task<int> RemoveSpecificPermissionInRole(Guid roleId, Guid permissionId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"delete from app_roles_permissions where ""RolesID""=@RID and ""PermissionsID""=@PID";
        return await conn.ExecuteAsync(sql, new { RID = roleId, PID = permissionId });
    }

    public async Task<IEnumerable<object>> GetRolePermissionsAsync(Guid roleId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"
            SELECT p.""ID"", p.""PermissionName""
            FROM app_permissions p
            INNER JOIN app_roles_permissions rp ON p.""ID"" = rp.""PermissionsID""
            WHERE rp.""RolesID"" = @RoleId";
        
        var permissions = await conn.QueryAsync(sql, new { RoleId = roleId });
        return permissions;
    }
}